
const {
  appId
} = wx.getAccountInfoSync().miniProgram;

const url = Object.is(appId, 'wx8d3dd00cdb1d0280') ? 'https://itao-tech.com/api-dev' : 'https://itao-tech.com/api';
const app = getApp();


let modalState = false;
const getModalState = () => modalState;
const setModalState = (arg) => {
  modalState = arg
};
const errorHandle = (msg) => {
  if (!getModalState()) {
    setModalState(true);
    wx.showModal({
      showCancel: false,
      title: '提示',
      content: msg || '请求错误！操作未完成',
      success(e) {
        if (e.confirm) {
          setModalState(false);
        }
      }
    })
  }
}
const toLogin = () => {
  const page = getCurrentPages();
  const path = page[0]?.route;
  //FIXED: 登录失败的状态码也是 401
  if (path?.endsWith('login')) {
    return
  }
  wx.showToast({
    title: '请先登录',
    icon:'none'
  })
  app.globalData.prevPage = page;
  wx.redirectTo({
    url: '/pages/login/login',
  })
}

const response = (value, successCallback, failCallback) => {
  const {
    statusCode,
    data,
    errMsg
  } = value;
  let res = null;
  switch (statusCode) {
    case 200:
      res = data;
      successCallback && successCallback(res);
      break;
    case 500:
      errorHandle(data?.message);
      failCallback && failCallback(data?.message);
      break;
    case 401:
      toLogin();
      failCallback && failCallback(data?.message);
      break;
    default:
      errorHandle(data?.message || errMsg);
      failCallback && failCallback(data?.message);
      break;
  }
}

export {
  url,
  response,
  errorHandle
}